﻿using Pay.Core;
using Pay.Data;
using Pay.DTO;
using Pay.IService;
using Pay.Service.Cache;
using Pay.TO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Pay.Service {
    public class TokenBazaarOrderService : ServiceBase, ITokenBazaarOrderService, IDisposable {
        private IUnitOfWork _iUnitOfWork;
        private ITokenBazaarProductService _iTokenBazaarProductService;
        private IShippingAddressService _iShippingAddressService;
        private IRedRecordService _iRedRecordService;
        private ISettingService _iSettingService;
        private ILogisticsDetailsService _iLogisticsDetailsService;
        private IMerchantService _iMerchantService;
        public TokenBazaarOrderService(IUnitOfWork iUnitOfWork, ITokenBazaarProductService iTokenBazaarProductService,
            IShippingAddressService iShippingAddressService, IRedRecordService iRedRecordService, ISettingService iSettingService, ILogisticsDetailsService iLogisticsDetailsService, IMerchantService iMerchantService) : base(iUnitOfWork) {
            _iUnitOfWork = iUnitOfWork;
            _iTokenBazaarProductService = iTokenBazaarProductService;
            _iShippingAddressService = iShippingAddressService;
            _iRedRecordService = iRedRecordService;
            _iSettingService = iSettingService;
            _iLogisticsDetailsService = iLogisticsDetailsService;
            _iMerchantService = iMerchantService;
        }
        /// <summary>
        /// 创建订单
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="merchantId"></param>
        /// <param name="shipAddressId"></param>
        /// <returns></returns>
        public bool CreateOrder(long productId, long merchantId, long shipAddressId) {
            var member = _iMerchantService.GetTokenUser(merchantId);
            if (member.disabled) {
                throw new ServerErrorException("您的账号已被禁用，不能进行购买");
            }
            if (!member.is_verify_no_card) {//实名认证未通过
                throw new ServerErrorException("您的账号实名认证未通过，请等待实名认证通过再进行购买");
            }
            var shipAddress = _iShippingAddressService.Get(shipAddressId);
            var product = context.TokenBazaarProduct.FindById(productId);
            if (product == null) throw new ServerErrorException("商品不存在");
            if (product.Num < 1) throw new ServerErrorException("商品已失效");
            if (product.MerchantId == merchantId) throw new ServerErrorException("自己不能购买自己的商品");
            var redRecord = context.RedRecord.FirstOrDefault(s => s.MerchantId == merchantId);
            if (redRecord == null) throw new ServerErrorException("红钻不足");
            if (redRecord.TotalRedDrill - redRecord.ConsumeRedDrill < product.Price) {
                throw new ServerErrorException("红钻不足");
            }
            product.Num -= 1;
            redRecord.FrozenRedDrill += product.Price;
            redRecord.ConsumeRedDrill += product.Price;
            TokenBazaarOrder order = new TokenBazaarOrder() {
                OrderNo = DtoHelper.GenerateOrderNumber(),
                ProductId = product.Id,
                BuyId = merchantId,
                Price = product.Price,
                Status = EBazaarOrderStatus.Received,
                CreateTime = DateTime.Now.ToUnix(),
                UpdateTime = DateTime.Now.ToUnix(),
                SellerId = product.MerchantId
            };
            TokenShipping shipping = new TokenShipping();
            shipping.ShipTo = shipAddress.ship_to;
            shipping.Phone = shipAddress.phone;
            shipping.RegionId = shipAddress.area_id;
            shipping.RegionName = shipAddress.region_name;
            shipping.Address = shipAddress.address;
            shipping.OrderId = order.Id;
            RedFrozenRecord fRecord = new RedFrozenRecord();
            fRecord.MerchantId = merchantId;
            fRecord.OrderId = order.Id;
            fRecord.RedDrill = product.Price;
            fRecord.CreateTime = DateTime.Now.ToUnix();
            context.TokenBazaarOrder.Add(order);
            context.TokenShipping.Add(shipping);
            context.RedFrozenRecord.Add(fRecord);
            int r = _iUnitOfWork.Commit("TokenBazaarProduct" + product.Id, "RedRecord" + redRecord.Id, "RedRecord" + redRecord.MerchantId);

            if (r > 0) {
                var msg_setting = _iSettingService.GetTokenSetting().msg;
                var sellmsg = msg_setting.FirstOrDefault(s => s.code == "bazaar_sell_buy");
                MessagePush sellMessage = new MessagePush() {
                    Title = sellmsg.name,
                    Content = string.Format(sellmsg.content, product.ProductName),
                    CreateTime = DateTime.Now.ToUnix(),
                    MerchantId = product.MerchantId,
                    ShortContent = string.Format(sellmsg.content, product.ProductName),
                    Type = MsgType.BazaarSellerSend,
                    Ext = "{}",
                    IsRead = false,
                    Filter = false,
                    ObjectId = order.Id,
                    Url = t_RequestMethod.token_url + "bazaarorder/orderdetail/" + order.Id
                };
                context.MessagePushs.Add(sellMessage);
                _iUnitOfWork.Commit("MessagePush" + product.MerchantId);
                try {
                    JPushHelp jPushHelp = new JPushHelp(t_RequestMethod.push_app_key, t_RequestMethod.push_app_secret);
                    jPushHelp.Push(sellMessage.Title, sellMessage.Content, (int)sellMessage.Type, sellMessage.ObjectId.Value, new List<string> { product.Merchant.Mobile }, sellMessage.Url);
                } catch {
                }
            }
            return r > 0;
        }
        public mall_model ValidateOrder(long productId, long merchantId, long shipAddressId, string wxOpenId,string ip) {
            var member = _iMerchantService.Get(merchantId);
            if (member.disabled) {
                throw new ServerErrorException("您的账号已被禁用，不能进行购买");
            }
            var shipAddress = _iShippingAddressService.Get(shipAddressId);
            var product = context.TokenBazaarProduct.FindById(productId);

            if (product == null) throw new ServerErrorException("商品不存在");
            if(product.MarketPrice<=0) throw new ServerErrorException("商品价格不正确");
            if (product.Num < 1) throw new ServerErrorException("商品已失效");
            if (product.MerchantId == merchantId) throw new ServerErrorException("自己不能购买自己的商品");
            var mall = new mall_model { order_no = DtoHelper.GenerateOrderNumber(), source_type = 3};
           
            var orderitems = new List<order_item_dto>();
            var dics = new Dictionary<string, object> {
                            { "cost_price",product.MarketPrice}
                        };
            var order_item = new order_item_dto() {
                product_id = 0,
                bazaar_product_id = product.Id,
                product_name = product.ProductName,
                unit_price = product.MarketPrice,
                market_price = product.MarketPrice,
                quantity = 1,
                sku_name = "",
                sku_id = 0,
                distribute_price = 0,
                thumbnails_url = product.MainImg,
                body = dics,
                order_item_type = 6,
                active_type = 0,
                product_activity_id = 0,
                red_drill = 0,
                isCashPay = true,
            };
            var orders = new List<order_dto>();
            var order = new order_dto {
                order_no = DtoHelper.GenerateOrderNumber(),
                status = OrderStatus.WaitPay,
                order_time = DateTime.Now,
                buy_id = merchantId,
                freight = 0,
                merchant_id = product.MerchantId,
                remark = "",
                order_type = 6,
                

            };
            orderitems.Add(order_item);
            order.order_items = orderitems;
            order.order_amount = product.MarketPrice*order_item.quantity;
            order.pay_amount = order.order_amount;
            order.red_drill = 0;
            orders.Add(order);
            mall.orders = orders;
            mall.bind_no = member.merchant_no;
            mall.orders.ForEach(c => {
                c.buyer = member;
            });
            
            mall.shipping = new shipping_model {
                address = shipAddress.address,
                id_card = shipAddress.id_card,
                real_name = shipAddress.real_name,
                area_id = shipAddress.area_id,
                city_id = shipAddress.city_id,
                phone = shipAddress.phone,
                province_id = shipAddress.province_id,
                region_name = shipAddress.region_name,
                ship_to = shipAddress.ship_to
            };
            mall.pay_channel = PayChannel.H5Pay;
            string product_name = orders.FirstOrDefault().order_items.FirstOrDefault().product_name;
            if (string.IsNullOrEmpty(product_name))
                product_name = string.Format("集市订单-{0}", DateTime.Now.ToString("yyyyMMddHHmmss"));
            mall.body = product_name;
            mall.req_method = 2;
            mall.pay_code = "H5Pay";
            mall.settle_type = "T1";
            mall.merchant_no = t_RequestMethod.merchant_no;
            mall.method = t_RequestMethod.TOKEN_MALL_PAY_HTML;
            mall.notify = string.Format("{0}/pay/h5_pay_notify", t_RequestMethod.api_url);
            mall.front_notify = string.Format("{0}/MyOrder/OrderList", t_RequestMethod.token_url);
            mall.openid = !string.IsNullOrEmpty(wxOpenId) ? wxOpenId : ip;
            mall.is_wx_pub_account_pay = !string.IsNullOrEmpty(wxOpenId) ? true : false;
            mall.nonce = DtoHelper.RandCode(10);
            mall.shipping_type = 1;
            mall.subject = "快捷支付";
            mall.timestamp = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
            mall.tran_amount = (Math.Round(product.MarketPrice * 100, 2)).ToString();
            return mall;
        }
        /// <summary>
        ///获取商品
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public token_bazaar_order_dto Get(long id) {
            var model = context.TokenBazaarOrder.Where(c => c.Id == id).FromCacheFirstOrDefault<TokenBazaarOrder, token_bazaar_order_dto>("TokenBazaarOrder" + id);
            return model;
        }
        /// <summary>
        /// 订单查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public PagedResult<token_bazaar_order_dto> Gets(BazaarOrderQuery query) {
            var filter = PredicateBuilder.True<TokenBazaarOrder>();
            if (query.merchant_type.HasValue && query.is_del.HasValue) {
                if (query.merchant_type == 1) {
                    if (query.is_del.HasValue) { filter = filter.And(c => c.IsBuyDel == query.is_del.Value); }
                    filter = filter.And(c => c.BuyId == query.merchant_id);
                } else {
                    if (query.is_del.HasValue) { filter = filter.And(c => c.IsSellDel == query.is_del.Value); }
                    filter = filter.And(c => c.SellerId == query.merchant_id);
                }
            }
            if (!string.IsNullOrEmpty(query.merchant_name)) {
                filter = filter.And(c => c.SellerMerchant.Name.Contains(query.merchant_name) ||
                c.SellerMerchant.Mobile.Contains(query.merchant_name) ||
                 c.BuyMerchant.Mobile.Contains(query.merchant_name) ||
                  c.BuyMerchant.Mobile.Contains(query.merchant_name));
            }
            if (!string.IsNullOrEmpty(query.product_name))
                filter = filter.And(c => c.TokenBazaarProduct.ProductName.Contains(query.product_name)||c.OrderNo==query.product_name);
            if (query.start_time.HasValue) {
                long startTime = query.start_time.Value.ToUnix();
                filter = filter.And(c => c.UpdateTime >= startTime);
            }
            if (query.end_time.HasValue) {
                long endTime = query.end_time.Value.AddDays(1).ToUnix();
                filter = filter.And(c => c.UpdateTime <= endTime);
            }

            if (query.status.GetValueOrDefault(-1) > -1) {
                filter = filter.And(c => c.Status == (EBazaarOrderStatus)query.status);
            }

            return context.TokenBazaarOrder.FromCachePaged<TokenBazaarOrder, token_bazaar_order_dto>(query.page, query.size, filter, orderBy => orderBy.OrderBy(c => c.Status).ThenByDescending(c => c.UpdateTime));
        }
        /// <summary>
        /// 删除订单
        /// </summary>
        /// <param name="id"></param>
        /// <param name="merchantId"></param>
        /// <param name="type">1 买家 2 卖家</param>
        /// <returns></returns>
        public bool Delete(long id, long merchantId, int type) {
            var filter = PredicateBuilder.True<TokenBazaarOrder>();
            filter = filter.And(s => s.Id == id);
            if (type == 1) { filter = filter.And(s => s.BuyId == merchantId); } else filter = filter.And(s => s.SellerId == merchantId);
            var model = context.TokenBazaarOrder.Where(filter).FirstOrDefault();
            if (model == null) throw new ServerErrorException("订单不存在");
            if (model.Status == EBazaarOrderStatus.Received || model.Status == EBazaarOrderStatus.Delivery) {
                throw new ServerErrorException("订单正在交易中不能删除");
            }
            if (type == 1)
                model.IsBuyDel = true;
            else model.IsSellDel = true;
            var r = _iUnitOfWork.Commit("TokenBazaarOrder" + id);
            return r > 0;
        }
        /// <summary>
        /// 卖家取消订单
        /// </summary>
        /// <param name="id"></param>
        /// <param name="merchantId"></param>
        /// <returns></returns>
        public bool Cancle(long id, long merchantId) {
            var model = context.TokenBazaarOrder.Where(s => s.Id == id && s.SellerId == merchantId).FirstOrDefault();
            if (model == null) throw new ServerErrorException("订单不存在");
            if (model.Status != EBazaarOrderStatus.Received) {
                throw new ServerErrorException("只有待发货订单才能取消");
            }
            model.Status = EBazaarOrderStatus.Cancle;
            model.FinishTime = DateTime.Now.ToUnix();
            model.UpdateTime = DateTime.Now.ToUnix();
            model.TokenBazaarProduct.Num += 1;
            var buyRedRecord = context.RedRecord.FirstOrDefault(s => s.MerchantId == model.BuyId);
            buyRedRecord.ConsumeRedDrill -= model.Price;
            buyRedRecord.FrozenRedDrill -= model.Price;
            RedFrozenRecord fRecord = new RedFrozenRecord();
            fRecord.MerchantId = model.BuyId;
            fRecord.OrderId = model.Id;
            fRecord.RedDrill = model.Price;
            fRecord.Type = 1;
            fRecord.CreateTime = DateTime.Now.ToUnix();
            var msg_setting = _iSettingService.GetTokenSetting().msg;
            var buymsg = msg_setting.FirstOrDefault(s => s.code == "bazaar_buy_cancle");
            //var sellmsg = msg_setting.FirstOrDefault(s => s.code == "bazaar_sell_cancle");
            MessagePush buyMessage = new MessagePush() {
                Title = buymsg.name,
                Content = string.Format(buymsg.content, model.TokenBazaarProduct.ProductName),
                CreateTime = DateTime.Now.ToUnix(),
                MerchantId = model.BuyId,
                ShortContent = string.Format(buymsg.content, model.TokenBazaarProduct.ProductName),
                Type = MsgType.BazaarRervSellerCancel,
                Ext = "{}",
                IsRead = false,
                Filter = false,
                ObjectId = model.Id,
                Url = t_RequestMethod.token_url + "bazaarorder/orderdetail/" + model.Id
            };
            //MessagePush sellMessage = new MessagePush() {
            //    Title = sellmsg.name,
            //    Content = string.Format(sellmsg.content, model.TokenBazaarProduct.ProductName),
            //    CreateTime = DateTime.Now.ToUnix(),
            //    MerchantId = model.SellerId,
            //    ShortContent = string.Format(sellmsg.content, model.TokenBazaarProduct.ProductName),
            //    Type = MsgType.None,
            //    Ext = string.Empty,
            //    IsRead = false,
            //    Filter = false
            //};
            context.MessagePushs.Add(buyMessage);
            //context.MessagePushs.Add(sellMessage);
            context.RedFrozenRecord.Add(fRecord);
            var r = _iUnitOfWork.Commit("TokenBazaarOrder" + id, "RedRecord" + buyRedRecord.Id, "RedRecord" + buyRedRecord.MerchantId, "TokenBazaarProduct" + model.ProductId, "MessagePush" + buyRedRecord.MerchantId);
            if (r > 0) {
                try {

                    JPushHelp jPushHelp = new JPushHelp(t_RequestMethod.push_app_key, t_RequestMethod.push_app_secret);
                    jPushHelp.Push(buyMessage.Title, buyMessage.Content, (int)buyMessage.Type, buyMessage.ObjectId.Value, new List<string> { model.BuyMerchant.Mobile }, buyMessage.Url);
                    //jPushHelp.Push(sellMessage.Title, sellMessage.Content, 1, sellMessage.Id, new List<string> { model.SellerMerchant.Mobile });
                } catch {
                }
            }
            return r > 0;
        }
        /// <summary>
        /// 系统取消交易
        /// </summary>
        /// <param name="id"></param>
        /// <param name="sysUserId"></param>
        /// <returns></returns>
        public bool SysCancle(long id, long sysUserId) {
            var model = context.TokenBazaarOrder.Where(s => s.Id == id).FirstOrDefault();
            if (model == null) throw new ServerErrorException("订单不存在");
            if (!(model.Status == EBazaarOrderStatus.Received||model.Status==EBazaarOrderStatus.Delivery)) {
                throw new ServerErrorException("只有待发货订单才能取消");
            }
            model.Status = EBazaarOrderStatus.Cancle;
            model.FinishTime = DateTime.Now.ToUnix();
            model.UpdateTime = DateTime.Now.ToUnix();
            model.TokenBazaarProduct.Num += 1;
            var manage = context.Manages.FindById(sysUserId);
            if (manage != null) { model.Remark = string.Format("系统取消交易******操作人：{0}****{1}", manage.Nick, manage.Mobile); } else { model.Remark = "系统取消交易"; }
            var buyRedRecord = context.RedRecord.FirstOrDefault(s => s.MerchantId == model.BuyId);
            buyRedRecord.ConsumeRedDrill -= model.Price;
            buyRedRecord.FrozenRedDrill -= model.Price;
            RedFrozenRecord fRecord = new RedFrozenRecord();
            fRecord.MerchantId = model.BuyId;
            fRecord.OrderId = model.Id;
            fRecord.RedDrill = model.Price;
            fRecord.Type = 1;
            fRecord.CreateTime = DateTime.Now.ToUnix();
            context.RedFrozenRecord.Add(fRecord);
            var r = _iUnitOfWork.Commit("TokenBazaarOrder" + id, "RedRecord" + buyRedRecord.Id, "RedRecord" + buyRedRecord.MerchantId, "TokenBazaarProduct" + model.ProductId);
            return r > 0;
        }
        /// <summary>
        /// 系统定时收货
        /// </summary>
        /// <returns></returns>
        public async Task<int> SysTaskRecevie() {
            int r = 0;
#if DEBUG
            long dt = DateTime.Now.AddMinutes(-5).ToUnix();
#else
              long dt = DateTime.Now.AddDays(-7).ToUnix();
#endif

            var orders = context.TokenBazaarOrder.Where(s => s.Status == EBazaarOrderStatus.Delivery && s.ShippingType == 0 && s.TokenShipping.ShippingTime.HasValue && s.TokenShipping.ShippingTime.Value < dt).ToList();
            if (orders.Count > 0) {
                List<RedRecordDetail> redRecords = new List<RedRecordDetail>();
                List<RedFrozenRecord> redFrozenRecoerds = new List<RedFrozenRecord>();
                List<string> tags = new List<string>();
                foreach (var item in orders) {
                    if (!string.IsNullOrEmpty(item.TokenShipping.ShipOrderNumber)) {
                        order_dto dto = new order_dto();
                        dto.shipping = new shipping_dto();
                        dto.shipping.express_no = item.TokenShipping.ExpressNo;
                        dto.shipping.express_company_name = item.TokenShipping.ExpressCompanyName;
                        dto.shipping.ship_order_number = item.TokenShipping.ShipOrderNumber;
                        var logistics_result = await _iLogisticsDetailsService.GetLogisticInfo(dto);
                        ///物流已签收
                        if (logistics_result.State == "3") {
                            item.Status = EBazaarOrderStatus.Finish;
                            item.FinishTime = DateTime.Now.ToUnix();
                            item.UpdateTime = DateTime.Now.ToUnix();
                            item.TokenBazaarProduct.Status = EBazaarProductStatus.Traded;
                            item.Remark = "系统自动定时确认收货";
                            var buyRedRecord = context.RedRecord.FirstOrDefault(s => s.MerchantId == item.BuyId);
                            var sellRedRecord = context.RedRecord.FirstOrDefault(s => s.MerchantId == item.SellerId);
                            RedRecordDetail buy_detail = new RedRecordDetail();
                            buy_detail.MerchantId = item.BuyId;
                            buy_detail.HorsePower = 0;
                            buy_detail.RedDrill = item.Price;
                            buy_detail.Type = 5;
                            buy_detail.IsReceive = true;
                            buy_detail.ReceiveTime = DateTime.Now.ToUnix();
                            buy_detail.CreateTime = DateTime.Now.ToUnix();
                            buy_detail.RedProductionTime = 0;
                            buy_detail.RedRecordId = buyRedRecord.Id;
                            RedRecordDetail sell_detail = new RedRecordDetail();
                            sell_detail.MerchantId = item.SellerId;
                            sell_detail.HorsePower = 0;
                            sell_detail.RedDrill = item.Price;
                            sell_detail.Type = 6;
                            sell_detail.IsReceive = true;
                            sell_detail.ReceiveTime = DateTime.Now.ToUnix();
                            sell_detail.CreateTime = DateTime.Now.ToUnix();
                            sell_detail.RedProductionTime = 0;
                            sell_detail.RedProductionTime = DateTime.Now.ToUnix();
                            sell_detail.RedRecordId = sellRedRecord.Id;
                            RedFrozenRecord fRecord = new RedFrozenRecord();
                            fRecord.MerchantId = item.BuyId;
                            fRecord.OrderId = item.Id;
                            fRecord.RedDrill = item.Price;
                            fRecord.Type = 1;
                            fRecord.CreateTime = DateTime.Now.ToUnix();
                            buyRedRecord.FrozenRedDrill -= item.Price;
                            sellRedRecord.TotalRedDrill += item.Price;
                            redRecords.Add(buy_detail);
                            redRecords.Add(sell_detail);
                            redFrozenRecoerds.Add(fRecord);
                            tags.AddRange(new string[] { "TokenBazaarOrder" + item.Id, "RedRecord" + buyRedRecord.Id, "RedRecord" + buyRedRecord.MerchantId, "RedRecord" + sellRedRecord.Id, "RedRecord" + sellRedRecord.MerchantId, "TokenBazaarProduct" + item.ProductId });
                        }
                    }
                }
                if (tags.Count > 0) {
                    context.RedRecordDetail.AddRange(redRecords);
                    context.RedFrozenRecord.AddRange(redFrozenRecoerds);
                    r = _iUnitOfWork.Commit(tags.ToArray());
                }
            }
            return r;


        }
        /// <summary>
        /// 买家收货
        /// </summary>
        /// <param name="id"></param>
        /// <param name="merchantId"></param>
        /// <returns></returns>
        public bool Receive(long id, long merchantId) {
            var model = context.TokenBazaarOrder.Where(s => s.Id == id && s.BuyId == merchantId).FirstOrDefault();
            if (model == null) throw new ServerErrorException("订单不存在");
            if (model.Status != EBazaarOrderStatus.Delivery) {
                throw new ServerErrorException("只有待收货订单才能确认收货");
            }
            model.Status = EBazaarOrderStatus.Finish;
            model.FinishTime = DateTime.Now.ToUnix();
            model.UpdateTime = DateTime.Now.ToUnix();
            model.TokenBazaarProduct.Status = EBazaarProductStatus.Traded;
            var buyRedRecord = context.RedRecord.FirstOrDefault(s => s.MerchantId == merchantId);
            var sellRedRecord = context.RedRecord.FirstOrDefault(s => s.MerchantId == model.SellerId);
            RedRecordDetail buy_detail = new RedRecordDetail();
            buy_detail.MerchantId = merchantId;
            buy_detail.HorsePower = 0;
            buy_detail.RedDrill = model.Price;
            buy_detail.Type = 5;
            buy_detail.IsReceive = true;
            buy_detail.ReceiveTime = DateTime.Now.ToUnix();
            buy_detail.CreateTime = DateTime.Now.ToUnix();
            buy_detail.RedProductionTime = 0;
            buy_detail.RedRecordId = buyRedRecord.Id;
            RedRecordDetail sell_detail = new RedRecordDetail();
            sell_detail.MerchantId = model.SellerId;
            sell_detail.HorsePower = 0;
            sell_detail.RedDrill = model.Price;
            sell_detail.Type = 6;
            sell_detail.IsReceive = true;
            sell_detail.ReceiveTime = DateTime.Now.ToUnix();
            sell_detail.CreateTime = DateTime.Now.ToUnix();
            sell_detail.RedProductionTime = 0;
            sell_detail.RedProductionTime = DateTime.Now.ToUnix();
            sell_detail.RedRecordId = sellRedRecord.Id;
            RedFrozenRecord fRecord = new RedFrozenRecord();
            fRecord.MerchantId = merchantId;
            fRecord.OrderId = model.Id;
            fRecord.RedDrill = model.Price;
            fRecord.Type = 1;
            fRecord.CreateTime = DateTime.Now.ToUnix();
            context.RedRecordDetail.Add(buy_detail);
            context.RedRecordDetail.Add(sell_detail);
            context.RedFrozenRecord.Add(fRecord);
            buyRedRecord.FrozenRedDrill -= model.Price;
            sellRedRecord.TotalRedDrill += model.Price;
            var msg_setting = _iSettingService.GetTokenSetting().msg;
            //var buymsg = msg_setting.FirstOrDefault(s => s.code == "bazaar_buy_receive");
            var sellmsg = msg_setting.FirstOrDefault(s => s.code == "bazaar_sell_receive");
            //MessagePush buyMessage = new MessagePush() {
            //    Title = buymsg.name,
            //    Content = string.Format(buymsg.content, model.TokenBazaarProduct.ProductName),
            //    CreateTime = DateTime.Now.ToUnix(),
            //    MerchantId = model.BuyId,
            //    ShortContent = string.Format(buymsg.content, model.TokenBazaarProduct.ProductName),
            //    Type = MsgType.None,
            //    Ext = string.Empty,
            //    IsRead = false,
            //    Filter = false
            //};
            MessagePush sellMessage = new MessagePush() {
                Title = sellmsg.name,
                Content = string.Format(sellmsg.content, model.TokenBazaarProduct.ProductName),
                CreateTime = DateTime.Now.ToUnix(),
                MerchantId = model.SellerId,
                ShortContent = string.Format(sellmsg.content, model.TokenBazaarProduct.ProductName),
                Type = MsgType.BazaarBuyerRerv,
                Ext = "{}",
                IsRead = false,
                Filter = false,
                ObjectId = model.Id,
                Url = t_RequestMethod.token_url + "bazaarorder/orderdetail/" + model.Id
            };
            //context.MessagePushs.Add(buyMessage);
            context.MessagePushs.Add(sellMessage);
            var r = _iUnitOfWork.Commit("TokenBazaarOrder" + id, "RedRecord" + buyRedRecord.Id, "RedRecord" + buyRedRecord.MerchantId, "RedRecord" + sellRedRecord.Id, "RedRecord" + sellRedRecord.MerchantId, "TokenBazaarProduct" + model.ProductId, "MessagePush" + model.SellerId);
            if (r > 0) {
                try {

                    JPushHelp jPushHelp = new JPushHelp(t_RequestMethod.push_app_key, t_RequestMethod.push_app_secret);
                    //jPushHelp.Push(buyMessage.Title, buyMessage.Content, 1, buyMessage.Id, new List<string> { model.BuyMerchant.Mobile });
                    jPushHelp.Push(sellMessage.Title, sellMessage.Content, (int)sellMessage.Type, sellMessage.ObjectId.Value, new List<string> { model.SellerMerchant.Mobile }, sellMessage.Url);
                } catch {
                }
            }
            return r > 0;
        }
        /// <summary>
        /// 系统确认收货
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool SysReceive(long id, long sysUserId) {
            var model = context.TokenBazaarOrder.Where(s => s.Id == id).FirstOrDefault();
            if (model == null) throw new ServerErrorException("订单不存在");
            if (model.Status != EBazaarOrderStatus.Delivery) {
                throw new ServerErrorException("只有待收货订单才能确认收货");
            }
            model.Status = EBazaarOrderStatus.Finish;
            model.FinishTime = DateTime.Now.ToUnix();
            model.UpdateTime = DateTime.Now.ToUnix();
            model.TokenBazaarProduct.Status = EBazaarProductStatus.Traded;
            var manage = context.Manages.FindById(sysUserId);
            if (manage != null) { model.Remark = string.Format("系统确认收货******操作人：{0}****{1}", manage.Nick, manage.Mobile); } else { model.Remark = "系统确认收货"; }
            var buyRedRecord = context.RedRecord.FirstOrDefault(s => s.MerchantId == model.BuyId);
            var sellRedRecord = context.RedRecord.FirstOrDefault(s => s.MerchantId == model.SellerId);
            RedRecordDetail buy_detail = new RedRecordDetail();
            buy_detail.MerchantId = model.BuyId;
            buy_detail.HorsePower = 0;
            buy_detail.RedDrill = model.Price;
            buy_detail.Type = 5;
            buy_detail.IsReceive = true;
            buy_detail.ReceiveTime = DateTime.Now.ToUnix();
            buy_detail.CreateTime = DateTime.Now.ToUnix();
            buy_detail.RedProductionTime = 0;
            buy_detail.RedRecordId = buyRedRecord.Id;
            RedRecordDetail sell_detail = new RedRecordDetail();
            sell_detail.MerchantId = model.SellerId;
            sell_detail.HorsePower = 0;
            sell_detail.RedDrill = model.Price;
            sell_detail.Type = 6;
            sell_detail.IsReceive = true;
            sell_detail.ReceiveTime = DateTime.Now.ToUnix();
            sell_detail.CreateTime = DateTime.Now.ToUnix();
            sell_detail.RedProductionTime = 0;
            sell_detail.RedProductionTime = DateTime.Now.ToUnix();
            sell_detail.RedRecordId = sellRedRecord.Id;
            RedFrozenRecord fRecord = new RedFrozenRecord();
            fRecord.MerchantId = model.BuyId;
            fRecord.OrderId = model.Id;
            fRecord.RedDrill = model.Price;
            fRecord.Type = 1;
            fRecord.CreateTime = DateTime.Now.ToUnix();
            context.RedRecordDetail.Add(buy_detail);
            context.RedRecordDetail.Add(sell_detail);
            context.RedFrozenRecord.Add(fRecord);
            buyRedRecord.FrozenRedDrill -= model.Price;
            sellRedRecord.TotalRedDrill += model.Price;
            var r = _iUnitOfWork.Commit("TokenBazaarOrder" + id, "RedRecord" + buyRedRecord.Id, "RedRecord" + buyRedRecord.MerchantId, "RedRecord" + sellRedRecord.Id, "RedRecord" + sellRedRecord.MerchantId, "TokenBazaarProduct" + model.ProductId);

            return r > 0;
        }
        /// <summary>
        /// 卖家发货
        /// </summary>
        /// <param name="id"></param>
        /// <param name="merchantId"></param>
        /// <returns></returns>
        public bool Deliver(TokenBazaarOrderShipModel shipModel) {
            if (!(shipModel.ship_type == 0 || shipModel.ship_type == 1)) {
                throw new ServerErrorException("请选择交付方式");
            }
            if (shipModel.ship_type == 0) {
                if (string.IsNullOrEmpty(shipModel.express_no)) {
                    throw new ServerErrorException("请选择物流公司");
                }
                if (string.IsNullOrEmpty(shipModel.ship_num)) {
                    throw new ServerErrorException("请填写物流单号");
                }
            }
            var model = context.TokenBazaarOrder.Where(s => s.Id == shipModel.id && s.SellerId == shipModel.merchant_id).FirstOrDefault();
            if (model == null) throw new ServerErrorException("订单不存在");
            if (model.Status != EBazaarOrderStatus.Received) {
                throw new ServerErrorException("只有待发货订单才能发货");
            }
            model.Status = EBazaarOrderStatus.Delivery;
            model.ShippingType = shipModel.ship_type;
            var TokenShipping = context.TokenShipping.FirstOrDefault(s => s.OrderId == model.Id);
            TokenShipping.ShippingTime = DateTime.Now.ToUnix();
            if (shipModel.ship_type == 0) {
                TokenShipping.ExpressNo = shipModel.express_no;
                TokenShipping.ExpressCompanyName = shipModel.express_company;
                TokenShipping.ShipOrderNumber = shipModel.ship_num;
            }
            model.UpdateTime = DateTime.Now.ToUnix();
            var msg_setting = _iSettingService.GetTokenSetting().msg;
            var buymsg = msg_setting.FirstOrDefault(s => s.code == "bazaar_buy_deliver");
            //var sellmsg = msg_setting.FirstOrDefault(s => s.code == "bazaar_sell_deliver");
            MessagePush buyMessage = new MessagePush() {
                Title = buymsg.name,
                Content = string.Format(buymsg.content, model.TokenBazaarProduct.ProductName),
                CreateTime = DateTime.Now.ToUnix(),
                MerchantId = model.BuyId,
                ShortContent = string.Format(buymsg.content, model.TokenBazaarProduct.ProductName),
                Type = MsgType.BazaarSellerDeliver,
                Ext = "{}",
                IsRead = false,
                Filter = false,
                ObjectId = model.Id,
                Url = t_RequestMethod.token_url + "bazaarorder/orderdetail/" + model.Id
            };
            //MessagePush sellMessage = new MessagePush() {
            //    Title = sellmsg.name,
            //    Content = string.Format(sellmsg.content, model.TokenBazaarProduct.ProductName),
            //    CreateTime = DateTime.Now.ToUnix(),
            //    MerchantId = model.SellerId,
            //    ShortContent = string.Format(sellmsg.content, model.TokenBazaarProduct.ProductName),
            //    Type = MsgType.None,
            //    Ext = string.Empty,
            //    IsRead = false,
            //    Filter = false
            //};
            context.MessagePushs.Add(buyMessage);
            //context.MessagePushs.Add(sellMessage);
            var r = _iUnitOfWork.Commit("TokenBazaarOrder" + model.Id, "MessagePush" + model.BuyId);
            if (r > 0) {
                try {

                    JPushHelp jPushHelp = new JPushHelp(t_RequestMethod.push_app_key, t_RequestMethod.push_app_secret);
                    jPushHelp.Push(buyMessage.Title, buyMessage.Content, (int)buyMessage.Type, buyMessage.ObjectId.Value, new List<string> { model.BuyMerchant.Mobile }, buyMessage.Url);
                    //jPushHelp.Push(sellMessage.Title, sellMessage.Content, 1, sellMessage.Id, new List<string> { model.SellerMerchant.Mobile });
                } catch {
                }
            }
            return r > 0;
        }
    }
}
